/**
 * Copyright 厦门中软海晟信息技术有限公司 版权所有 违者必究 2019
 */
package com.vijos;

/**
 * @author : sunzb(sunzb@hsit.com.cn)
 * @date: 2019/4/18
 */
//数独验证
public class P3_4_1335 {

    public static boolean test(int[][] input) {
        dataVerify(input);
        // 行、列遍历
        for (int i = 0; i < 9; i++) {
            int[] row = input[i];
            int[] flagsRow = new int[10];
            int[] flagsCol = new int[10];
            for (int j = 0; j < 9; j++) {
                int valueRow = row[j];
                int valueCol = input[j][i];
                if (flagsRow[valueRow] == 1) {
                    return false;
                }
                if (flagsCol[valueCol] == 1) {
                    return false;
                }
                flagsRow[valueRow] = 1;
                flagsCol[valueCol] = 1;
            }
        }
        // 九宫格遍历
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                int startRow = 3 * i;
                int startCol = 3 * j;
                int[] flags = new int[10];
                for (int row = startRow; row < startRow + 3; row++) {
                    for (int col = startCol; col < startCol + 3; col++) {
                        int value = input[row][col];
                        if (flags[value] == 1) {
                            return false;
                        }
                        flags[value] = 1;
                    }
                }
            }
        }
        return true;
    }

    private static void dataVerify(int[][] input) {
        if (input.length != 9) {
            throw new RuntimeException("列数不对");
        }
        if (input[0].length != 9) {
            throw new RuntimeException("行数不对");
        }
    }

    public static void main(String[] args) {
        System.out.println(test(new int[][]{
                {5, 8, 1, 4, 9, 3, 7, 6, 2},
                {9, 6, 3, 7, 1, 2, 5, 8, 4},
                {2, 7, 4, 8, 6, 5, 9, 3, 1},
                {1, 2, 9, 5, 4, 6, 3, 7, 8},
                {4, 3, 6, 1, 8, 7, 2, 9, 5},
                {7, 5, 8, 3, 2, 9, 1, 4, 6},
                {8, 9, 2, 6, 7, 1, 4, 5, 3},
                {6, 1, 5, 9, 3, 4, 8, 2, 7},
                {3, 4, 7, 2, 5, 8, 6, 1, 9}
        }));
        System.out.println(test(new int[][]{
                {1, 2, 3, 4, 5, 6, 7, 8, 9},
                {2, 3, 4, 5, 6, 7, 8, 9, 1},
                {3, 4, 5, 6, 7, 8, 9, 1, 2},
                {4, 5, 6, 7, 8, 9, 1, 2, 3},
                {5, 6, 7, 8, 9, 1, 2, 3, 4},
                {6, 7, 8, 9, 1, 2, 3, 4, 5},
                {7, 8, 9, 1, 2, 3, 4, 5, 6},
                {8, 9, 1, 2, 3, 4, 5, 6, 7},
                {9, 1, 2, 3, 4, 5, 6, 7, 8}
        }));
    }
}
